package com.sjr.easy.chat.config;

import com.sjr.easy.chat.utils.TraceUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;

import java.io.IOException;

public class TraceWebServletConfiguration {

    public static class WebServletTraceFilter implements jakarta.servlet.Filter {

        private final Logger webServletTraceFilterLogger = LoggerFactory.getLogger(WebServletTraceFilter.class);

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            Filter.super.init(filterConfig);
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            try {
                String traceId = null;
                String spanId = TraceUtils.generateId();
                if (request instanceof HttpServletRequest) {
                    traceId = ((HttpServletRequest) request).getHeader(TraceUtils.HTTP_TRACE_ID_KEY);
                }
                if (StringUtils.isEmpty(traceId)) {
                    traceId = TraceUtils.generateId();
                }
                TraceUtils.runWithTracer(() -> {
                    filterChain.doFilter(request, response);
                    return null;
                }, new TraceUtils.TraceInfo(traceId, spanId));
            } catch (Throwable e) {
                if (e instanceof IOException) {
                    throw (IOException) e;
                }
                if (e instanceof ServletException) {
                    throw (ServletException) e;
                }
                webServletTraceFilterLogger.error("Error", e);
            }
        }

        @Override
        public void destroy() {
            Filter.super.destroy();
        }
    }

    @Bean
    public FilterRegistrationBean<WebServletTraceFilter> WebServletTraceFilterConfig() {
        FilterRegistrationBean<WebServletTraceFilter> result = new FilterRegistrationBean<>();
        result.setFilter(new WebServletTraceFilter());
        result.setOrder(Ordered.HIGHEST_PRECEDENCE);
        result.setName("WebServletTraceFilter");
        return result;
    }


}
